package com.example.demo38inheritablethreadlocal.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
public class HelloController {

    /**
     * SecurityContextHolder 默认策略：MODE_THREADLOCAL，使用 ThreadLocal
     *
     * 配置系统参数 -Dspring.security.strategy=MODE_INHERITABLETHREADLOCAL
     * SecurityContextHolder 策略：MODE_INHERITABLETHREADLOCAL，
     * 原理：使用 InheritableThreadLocal，子线程也可以获取用户登录信息
     */
    @GetMapping("/hello")
    public void hello() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        System.out.println("name = " + name);
        System.out.println("authorities = " + authorities);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                if(authentication != null) {
                    String name = authentication.getName();
                    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
                    String threadName = Thread.currentThread().getName();
                    System.out.println(threadName + ":name = " + name);
                    System.out.println(threadName + ":authorities = " + authorities);
                }
            }
        }).start();
    }

}
